<template>
  <div class="demo_sty">
    <el-scrollbar style="height: 100%" >
      <div class="return">
        <span><i class="el-icon-back"></i>   返回</span>
      </div>
      <div class="separator_sty"></div>
      <div class="form_sty">
        <el-form :model="orderform"  ref="orderform" :rules="orderformRules"  label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item  label="主题">
                <el-input v-model="orderform.orderTheme" placeholder="优品创意公司第一次合作"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="对应合同" prop="contractByContractId.contractName">
                <el-input  v-model="orderform.contractByContractId.contractName" placeholder="优品创意公司" v-on:click.native="add"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="对应机会">
                <el-select v-model="busName" placeholder="机会列表" style="width:217px">
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="订单编号">
                <el-input readonly v-model="orderform.orderName" placeholder="2002201533"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下单时间" prop="orderTime">
                <el-date-picker type="date" placeholder="选择日期" v-model="orderform.orderTime":pickerOptions="pickerOptions" style="width: 217px;"></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="最晚发货" prop="deliveryTime">
                <el-date-picker type="date" placeholder="选择日期"  v-model="orderform.deliveryTime":pickerOptions="pickerOptions" style="width: 217px;"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="签约人">
                <el-input  v-model="orderform.customerName" placeholder="王志杰"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所有者">
                <el-input readonly v-model="orderform.empId.empName" placeholder="陈默"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出库途径" prop="outboundType">
                <el-select  v-model="orderform.outboundType"  placeholder="出库途径" style="width:217px">
                  <el-option label="快递" value="快递"></el-option>
                  <el-option label="店面提车" value="店面提车"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="总金额">
                <el-input readonly v-model="orderform.orderTotal"  placeholder="12000,000"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="回款金额">
                <el-input readonly  v-model="orderform.receivableOrder"  placeholder="5000,000"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="付款方式" prop="orderPayment">
                <el-select v-model="orderform.orderPayment" value-key="termsId">
                  <el-option v-for="met in paymentsList" :key="met.termsId" :label="met.termsName" :value="met.termsId">

                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="报价单编号">
                <el-input v-model="quoName" placeholder="12000,000" v-on:click.native="show"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="收货人" >
                <el-input v-model="consName" placeholder="12000,000" v-on:click.native="consigneeInfo()"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="16">
              <el-form-item label="状态" >
                执行中
               <!-- <el-radio-group v-model="orderform.orderState" >
                  <el-radio label="1"  >执行中</el-radio>
                  <el-radio label="2" >结束</el-radio>
                  <el-radio label="3">意外终止</el-radio>
                </el-radio-group>-->
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注 ">
                <el-input type="textarea" v-model="orderform.orderNoteinfo"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label=" ">
            <el-button  style="margin: 0 0 0 445px;" type="primary" @click="onSubmit2">保存</el-button>
          </el-form-item>
        </el-form>

        <div class="separator_sty"></div>
        <!--产品区域--->
        <div style="border: 2px solid #E9EEF3;padding:0 0 10px 0">
          <el-collapse v-model="activeNames" @change="handleChange">
            <el-collapse-item title="订单详情" name="2">
              <div style="width:95%;height:400px;margin:0 auto;overflow-y: auto">
                <el-table :data="productList" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                          style="width: 97%;margin-top: 10px;">
                  <el-table-column  prop="zproductByProductId.productName"  label="产品名称" >
                  </el-table-column>
                  <el-table-column  prop="zproductByProductId.prModel"   label="型号"  >
                  </el-table-column>
                  <el-table-column  prop="detPrice"  label="价格">
                  </el-table-column>
                  <el-table-column label="折扣%" prop="detDiscount">
                  </el-table-column>
                  <el-table-column label="数量" prop="detNum">

                  </el-table-column>
                 <!-- <el-table-column  label="数量" width="160" align="center">
                    <template slot-scope="s">
                      <el-input-number v-model="s.row.detNum"  :min="1" :max="10" size="small" @change="smallPrice(s.$index,s.row)"></el-input-number>
                    </template>
                  </el-table-column>-->
                  <el-table-column label="单位"   prop="psUnit">
                  </el-table-column>
                  <el-table-column label="小计"  prop="detTotal">
                  </el-table-column>
                  <!--<el-table-column label="操作" width="130" align="center">
                    <template slot-scope="d">
                      <el-button type="text" size="small" icon="el-icon-delete" @click="deleteGood(d.row)"></el-button>
                    </template>
                  </el-table-column>-->
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

        <div>
          <!--合同列表 isCus-->
          <el-dialog title="选择合同" :visible.sync="customerVisable" width="60%">
            <el-row>
              <el-col>
                <el-input  placeholder="请输入合同名称" v-model="customerInfo" @change="searchCustomer"  suffix-icon="el-icon-search" style="width:200px;">
                </el-input>
              </el-col>
              <el-col>
                <el-table  :data="contractList" height="250" style="width: 100%">
                  <el-table-column width="55">
                    <template slot-scope="scope">
                      <el-radio v-model="radio" :label="scope.row.contractId" @change="getCustomerRow(scope.row)">
                        {{''}}
                      </el-radio>
                    </template>
                  </el-table-column>
                  <el-table-column prop="customerByCustomId.cusName" label="客户名称" >
                  </el-table-column>
                  <el-table-column prop="contractTheme" label="合同主题">
                  </el-table-column>
                  <el-table-column prop="contractName" label="合同编号">
                  </el-table-column>
                  <el-table-column prop="effectTime" label="创建时间">
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col>
                <el-pagination  @size-change="handleSizeChange1"  @current-change="changePage1" :current-page.sync="currentPage1"
                                :page-sizes="pageSizes1" :page-size="pageSize1" layout="total, sizes, prev, pager, next, jumper"
                                :total="totalSize1" style="float: right;margin-top: 10px;">
                </el-pagination>
              </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="customerOK">确 定</el-button>
        <el-button @click="customerVisable = false">取 消</el-button>
      </span>
          </el-dialog>

          <!--收货人信息-->
          <el-drawer
            :visible.sync="drawer"
            :direction="direction"
            size="30%">
            <span style="margin-left: 10px" @click="gotoCustomer">收货地址</span>
            <div class="div_sty">
              <el-row>
                <el-col :span="22" :offset="1" v-for="(cons, index) in receList" style="margin-bottom: 10px" :key="index">
                  <el-card :body-style="{ padding: '4px' }">
                    <div @click="cardevent(cons)">
                      <div style="padding: 14px;">
                        <el-row>
                          <el-col>
                            <span style="font-size: 20px">{{cons.consigneeName}}</span> {{cons.rcPhone}}
                          </el-col>
                        </el-row>
                        <div style="border: 1px solid #42b983 ;width: 95%;margin-top: 10px;margin-bottom: 10px"></div>
                        <el-row>
                          <el-col>
                            <span style="color: #20a0ff">{{cons.rcAddressProvince}} {{cons.rcAddressCity}} {{cons.rcAddressArea}} {{cons.rcAddressDetailed}}</span>
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
            <!--<el-table
              ref="tableProduct"
              :data="productList"
              style="width:90%;margin-left: 10px;margin-top: 10px;">

            </el-table>-->
            <!--
                        <el-button type="primary" style="float:right;margin-top: 10px;margin-right: 40px; margin-right: 45%" @click="confirmList">确定</el-button>
            -->
          </el-drawer>
        </div>
      </div>
    </el-scrollbar>

  </div>
</template>

<script>
  import {formatTimeToStr} from '../assets/format'

  export default {
    name: 'Csdemo',
    data(){
      var checkedDeliveryTime = (rule, value, callback) => {
        if(this.orderform.orderTime>value){
          callback(new Error('最晚发货时间不规范！！'));
        }else {
          callback();
        }
      }
      return{
        orderformRules:{//表单验证
          'contractByContractId.contractName' :[
            { required: true, message: '请选择合同', trigger: 'change' },
          ],
          deliveryTime:[
            { required: true, message: '请选择时间', trigger: 'change'},
            { validator:checkedDeliveryTime,trigger: 'change' }
          ],
          orderTime:[
            { required: true, message: '请选择时间', trigger: 'change'}
          ],
          outboundType:[
            { required: true, message: '请选择出库方式', trigger: 'change'}
          ],
          orderPayment:[
            { required: true, message: '请选择付款方式', trigger: 'change'}
          ],

        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
        thereName:'',
        activeNames: [1],//
        consName:'',//收货人名称
        customId:'',//客户id
        busName:"",//对应机会名称
        quoName:"",//报价单名称
        orderform:{
          orderTheme:'',//主题
          orderName:'',//订单单号
          orderState:'',//订单状态
          orderTime:'',//下单时间
          deliveryTime:'',//最晚发货时间
          orderTotal:'',//总金额
          receivableOrder:'',//已经回款金额
          orderPayment:'',//付款方式id
          businesId3:'',//对应机会id
          quotationId:'',//报价单id
          consigneeId:'',//收货联系人id
          customerName:'',//签约人
          customerByCustomId:{
            customId:'',
            cusName:'',
          },//客户id
          orderNoteinfo:'',//备注
          outboundType:'',//出库方式
          contractByContractId:{
            contractId:'',//合同id
            contractName:''//合同名称
          },//合同
          empId:{
            employeesId:'',//员工id
            empName:''//员工名字
          },
          orderdetailsByOrderId:[],//产品信息
        },
        receList:[],//收货人信息
        contractList:[],//合同信息
        productList:[],//产品列表
        productDetails:[],

        //===========
        direction: 'rtl',//左弹出
        drawer: false,//弹框
        offerInfo:[],//报价单信息
        info:'',
        culinkManList:[],//对应联系人
        paymentsList:[],//付款列表
        pageSizes1:[4, 8, 12],//可选择的页大小
        currentPage1:1,//当前页
        pageSize1:0,//页大小
        totalSize1:0,//总页数
        currentPage2:1,//报价单当前页
        pageSize2:0,//报价单页大小
        totalSize2:0,//报价单总页数
        input10:'',//'报价单查询',
        customerInfo:'',//客户搜索
        addformVisable:false,//报价单弹框显示
        customerVisable:false,//客户选择
        radio:'',//选中合同id
        offerRadio:'',//报价单id
        cusList:[],//选中客户信息
        opportunityList:[],//对应机会列表
        userInfo:{
          employeesId:0,//员工id
          empName:''//员工名称
        },
        contName:''
      };
    },
    created :function() {
      this.orderform.orderState="1";
      this.userInfo=JSON.parse(sessionStorage.getItem('user'));
      this.orderform.empId.employeesId=this.userInfo.employeesId;
      this.orderform.empId.empName=this.userInfo.empName;
      this.pageSize1=this.pageSizes1[0];//取到可改变页数大小的第一个页数
      this.inDateCustomer(this.currentPage1,this.pageSize1,this.customerMc,this.userInfo.employeesId);
      this.payments();
      this.kpl();
      this.orderNameEvent();
      this.orderform.receivableOrder=0.00;
    },
    methods: {
      gotoCustomer(){
          this.$router.push({
            path: '/customerview',
            query: {
              customId:this.orderform.customerByCustomId.customId
            }
          })

      },
      orderNameEvent(){
        this.$axios.get("http://localhost:8088/order_name").then(v=>{

          this.orderform.orderName=v.data;
        }).catch();
      },
      //将数据转换成指定数据格式
      kpl(){
        for (let i = 0; i <this.productList.length ; i++) {
          let val = this.productList[i];
          this.$set(val,'prName',this.productList[i].zproductByProductId.productName)//此处为重点
          this.$set(val,'prUnit',this.productList[i].psUnit)//此处为重点
          this.$set(val,'prsPrice',this.productList[i].detPrice)//此处为重点
          this.$set(val,'speColor',this.productList[i].zproductByProductId.prModel)
          this.$set(val,'detPrid',this.productList[i].prsId)
          this.productDetails.push(val);
        }
      },
      total(){
        let tatalMoney=0;
        this.productList.forEach((item,i)=>{
          tatalMoney=tatalMoney+item.detTotal;
        })
        this.orderform.orderTotal=tatalMoney;
      },
      //产品计算小计
      smallPrice(index,row){
        let price=0;//小计
        if(row.detDiscount=='0.00'){//不享受折扣
          //售价*数量
          price=parseFloat(row.detPrice).toFixed(2)*row.detNum;
          this.total();
        }else{//享受折扣
          //售价*折扣*数量
          price=parseFloat(row.detPrice).toFixed(2)*parseFloat(row.detDiscount).toFixed(2)*row.detNum;
        }
        this.productList[index].detTotal=price;//重新给小计赋值
        this.total();

      },
      //删除产品
      deleteGood(row){
        this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log("详情id:"+row.detId);
          //判断产品是刚添加的还是该客户已经有的产品
          this.productList.forEach((item,i) =>{
            if(item.prsId==row.prsId){
              this.productList.splice(i,1);
              this.total();
            }
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //产品卡片
      handleChange (val) {
        console.log(val);
      },
      //收货人信息确定
      cardevent(row){
        this.orderform.consigneeId=row.rcId;
        this.consName=row.consigneeName;
        this.drawer =false;
      },
      //收货人信息
      consigneeInfo(){
        this.print("客户id"+this.orderform.customerByCustomId.customId);
        if(this.orderform.customerByCustomId.customId=='' ||this.orderform.customerByCustomId.customId==undefined){
          this.$message("尚未选择合同！！！");
        }else {
          this.$axios.get("http://localhost:8088/rece_info",{params:{cusId:this.orderform.customerByCustomId.customId}}).then(v=>{
            this.receList=v.data;
            this.drawer = true;
          }).catch()
        }
      },
      //收货人弹框
      consignee(){
        this.drawer = true;
      },
      //付款方式
      payments(){
        this.$axios.get("http://localhost:8088/Payment_detail").then(v=>{
            this.paymentsList=v.data;
            this.termsPayment=v.data;
          }
        ).catch()
      },
      //合同选择弹框显示
      add(){
        this.customerVisable=true;
      },
      //合同分页查询
      inDateCustomer(currentPage1,pageSize1,customerMc,userId){
        this.$axios.get("http://localhost:8088/order_contr",
          {params:{page:currentPage1,size:pageSize1,name:customerMc,userId:userId}}).then(v=>{
          this.contractList=v.data.rows;
          this.totalSize1=v.data.total;
        }).catch()
      },
      //合同名称模糊查询
      searchCustomer(){
        this.print("value"+this.customerInfo);
        this.inDateCustomer(1,this.pageSize1,this.customerInfo,this.userInfo.employeesId);
      },
      //改变合同分页的页码
      changePage1(val){
        this.inDateCustomer(val,this.pageSize1,this.customerMc,this.userInfo.employeesId);
      },
      //改变合同分页的每页页数
      handleSizeChange1(val){
        this.inDateCustomer(1,val,this.customerMc,this.userInfo.employeesId);
      },
      //确定合同
      customerOK(){
        this.customerVisable=false;
        this.radio=this.cusList[0].customId;
        this.orderform.contractByContractId.contractId=this.cusList[0].contractId;//合同编号
        this.orderform.contractByContractId.contractName=this.cusList[0].contractName;//合同名称
        this.orderform.businesId3=this.cusList[0].businessInfoByBusinesId.businesId;//对应机会id
        this.busName=this.cusList[0].businessInfoByBusinesId.businessName;//对应机会名称
        this.orderform.quotationId=this.cusList[0].offerByOfferId2.offerId2;//报价单id
        this.quoName=this.cusList[0].offerByOfferId2.offerNumber;//报价单名称
        this.orderform.customerName=this.cusList[0].customerName;//签约人
        this.orderform.customerByCustomId.customId=this.cusList[0].customerByCustomId.customId;//客户id
        this.productInfo(this.orderform.quotationId);//产品信息
        this.thereName=this.cusList[0].customerByCustomId.cusName;
        this.$message("id"+this.cusList[0].customerByCustomId.cusName);
      },

      //获取报价单指定产品
      productInfo(offerId){
        this.$axios.get("http://localhost:8088/buInfo/businessDatails",
          {params:{businesId:this.orderform.businesId3}}).then(v=>{
          this.productList=v.data;
          this.total();
        }).then()
      },
      //客户单选框选中的行
      getCustomerRow(val){
        this.cusList=[];//先清空
        this.contName='';
        this.contName=val.contractTheme;
        this.cusList.push(val);
      },
      //报价单查询弹框
      show(){
        this.addformVisable=true;
      },
      confirmList () {
        this.drawer = false;
      },
      //报价单单选框选中行
      getOfferRow(val){
        this.offerInfo=[];
        this.offerInfo.push(val);
      },
      //表单2提交
      onSubmit2() {
        this.$refs["orderform"].validate((valid) => {
          if (valid) {
            this.kpl();
            this.$axios.post("http://localhost:8088/save_ordertt",{
              orderTheme:this.orderform.orderTheme,
              orderName:this.orderform.orderName,//订单单号
              orderState:this.orderform.orderState,//订单状态
              orderTime:this.orderform.orderTime,//下单时间
              deliveryTime:this.orderform.deliveryTime,//最晚发货时间
              orderTotal:this.orderform.orderTotal,//总金额
              receivableOrder:this.orderform.receivableOrder,//已经回款金额
              orderPayment:this.orderform.orderPayment,//付款方式id
              businesId3:this.orderform.businesId3,//对应机会id
              quotationId:this.orderform.quotationId,//报价单id
              consigneeId:this.orderform.consigneeId,//收货联系人id
              customerByCustomId:this.orderform.customerByCustomId,
              orderNoteinfo:this.orderform.orderNoteinfo,//备注
              outboundType:this.orderform.outboundType,//出库方式
              contractByContractId:this.orderform.contractByContractId,
              empId:this.orderform.empId,
              customerName:this.orderform.customerName,//签约人
              orderdetailsByOrderId:this.productDetails,//产品信息
            }).then(v=>{
              this.orderform={
                orderTheme:'',//主题
                  orderName:'',//订单单号
                  orderState:'',//订单状态
                  orderTime:'',//下单时间
                  deliveryTime:'',//最晚发货时间
                  orderTotal:'',//总金额
                  receivableOrder:'',//已经回款金额
                  orderPayment:'',//付款方式id
                  businesId3:'',//对应机会id
                  quotationId:'',//报价单id
                  consigneeId:'',//收货联系人id
                  customerName:'',//签约人
                  customerByCustomId:{
                  customId:'',
                    cusName:'',
                },//客户id
                orderNoteinfo:'',//备注
                  outboundType:'',//出库方式
                  contractByContractId:{
                  contractId:'',//合同id
                    contractName:''//合同名称
                },//合同
                empId:{
                  employeesId:'',//员工id
                    empName:''//员工名字
                },
                orderdetailsByOrderId:[],//产品信息
              }
              this.$router.push({path:'/ordepage'})
            }).catch()
          }
          })
      },
    },
    filters: {
      formatDate: function (time) {
        if (time != null && time != "") {
          var date = new Date(time);
          return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
        } else {
          return "";
        }
      }
    },
    watch: {
      'orderform.contractByContractId.contractName':function () {
        var aData = new Date();
        this.value =aData.getFullYear() + "-" + (aData.getMonth() + 1) + "-" + aData.getDate();
        this.orderform.orderTheme=this.value+"["+this.thereName+"订单"+"]";
      }
    }
  }
</script>

<style scoped>
  .div_sty{
    border: 1px solid #D3DCE6;
    overflow-y: auto;
    margin: 10px 0 10px 0;
    min-height: 100px;
    max-height: 500px;
    border-radius: 5px
  }
  .form_sty>>>.el-form-item__label{
    text-align: left;
    padding: 0 0 0 7px;
  }

  .form_sty>>>.el-form-item{
    margin: 10px 1px 1px ;
    padding: 10px 1px 1px 1px;
  }
  .form_sty>>>.el-dialog__body{
    padding:5px 20px;
  }
  .main_sty{
    border: 1px solid red;
    width: 100%;
  }
  .demo_sty{
    border:1px solid #ccc;
    width:100%;
    height: 545px;
    background: white;
    border-radius: 5px;
    box-shadow:#ccc 0px 0px 10px;
    overflow:hidden;

  }
  .return{
    border-right:1px solid #ccc;
    width:70px;
    color:#777;
    font-size: 13px;
    margin-left:10px;
    margin-top:10px;
    cursor: pointer;

  }
  .return:hover{
    color:#409eff;
    font-max-size: 10px;
  }
  .form_sty{
    border:1px solid #FFFFFF;
    background-color: #FFFFFF;
  }
  .el-form-item{
    padding: 20px 100px 0 10px;
  }
  .el-input{
    width: 50%;
    float: left;
    width: 217px;
  }
  .separator_sty{
    border:1px solid #409eff;
    width: 95%;
    margin: 10px auto;
  }
</style>
